package com.istock.user.controller.vue;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.istock.base.common.api.model.ApiBaseResponse;
import com.istock.base.common.api.model.PageInfo;
import com.istock.base.common.api.model.RetStatusEnum;
import com.istock.union.user.client.SSOClientUtils;
import com.istock.union.user.model.Constants;
import com.istock.union.user.model.MenuInfo;
import com.istock.union.user.model.OperLog;
import com.istock.union.user.model.SecurityChecker;
import com.istock.union.user.model.ext.ExtMenuInfo;
import com.istock.union.user.service.MenuInfoService;

@Controller
@RequestMapping("/s/menuInfo")
public class VueMenuInfoController {
	
	private static final Logger logger = LoggerFactory.getLogger(VueMenuInfoController.class);
	
	@Autowired
    private MenuInfoService menuService;

	/**
     * 加载菜单列表 有根节点
     */
    @RequestMapping("/menuTree")
    @ResponseBody
    public ApiBaseResponse<List<ExtMenuInfo>> menuTree() {
        List<MenuInfo> items = menuService.findAllMenu();

        ExtMenuInfo root = new ExtMenuInfo();
        root.setId("0");
        root.setName("主目录");
        root.setChildren(queryChildrenMenu("0",items));

        List<ExtMenuInfo> result = new ArrayList<>();
        result.add(root);

        return new ApiBaseResponse<>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, 
                Constants.API_RESPONSE_SUCCESS_MESSAGE, result);
    }

    private List<ExtMenuInfo> queryChildrenMenu(String parentId, List<MenuInfo> sourceList) {
        List<ExtMenuInfo> infos = new ArrayList<>();
        List<MenuInfo> menuList = new ArrayList<>();
        for(MenuInfo menuInfo:sourceList){
            if(menuInfo.getParentId().equals(parentId)){
                menuList.add(menuInfo);
            }
        }
        if (CollectionUtils.isEmpty(menuList)) {
            return infos;
        }
        for (MenuInfo menuInfo : menuList) {
            ExtMenuInfo extMenuInfo = new ExtMenuInfo();
            extMenuInfo.setId(menuInfo.getId());
            extMenuInfo.setName(menuInfo.getMenuName());
            List<ExtMenuInfo> childrenMenu = this.queryChildrenMenu(menuInfo.getId(),sourceList);
            extMenuInfo.setChildren(childrenMenu);
            infos.add(extMenuInfo);
        }
        return infos;
    }

    /**
     * 加载菜单列表（父子结构）
     */
    @RequestMapping("/allMenuTreeNew")
    @ResponseBody
    public ApiBaseResponse<List<ExtMenuInfo>> allMenuTreeNew() {
        List<ExtMenuInfo> tree = menuService.allMenuTreeNew();
        return new ApiBaseResponse<List<ExtMenuInfo>>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, 
                Constants.API_RESPONSE_SUCCESS_MESSAGE, tree);
    }

    /**
     * 加载角色菜单列表（菜单Id）
     */
    @RequestMapping("/roleMenuTreeNew")
    @ResponseBody
    public ApiBaseResponse<List<String>> roleMenuTreeNew(String roleId) {
        logger.info("query role munuList,roleId:{}", roleId);
        List<String> strings = menuService.roleMenuTreeNew(roleId);
        Set<String> menuIds = new HashSet<String>(strings);
        return new ApiBaseResponse<List<String>>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, 
                Constants.API_RESPONSE_SUCCESS_MESSAGE, new ArrayList<String>(menuIds));
    }
    
    private String MENU_ROOT_ID = "0";
    /**
     * 新增保存菜单
     */
    @SecurityChecker("user:menuInfo:add")
    @RequestMapping("/add")
    @ResponseBody
    @OperLog(functionName = "authority.page.add", menuName = "authority.menu.menuInfo")
    public ApiBaseResponse<Boolean> addSave(MenuInfo menuInfo) {
        try {
            menuInfo.setCreateBy(SSOClientUtils.getInstance().findCurrentUser().getUserName());
            if (StringUtils.isBlank(menuInfo.getParentId())) {
                menuInfo.setParentId(MENU_ROOT_ID);
            }
            if (StringUtils.isBlank(menuInfo.getUrl())) {
                menuInfo.setUrl("#");
            }
            menuService.saveMenuInfo(menuInfo);
            return new ApiBaseResponse<Boolean>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, 
                    Constants.API_RESPONSE_SUCCESS_MESSAGE, true);
        } catch (Exception e) {
            logger.error("insert menu info error, cause ", e);
            return new ApiBaseResponse<Boolean>(RetStatusEnum.FAIL,Constants.API_RESPONSE_FAIL_CODE, 
                    Constants.API_RESPONSE_FAIL_MESSAGE, false);
        }
    }
    
    /**
     * 修改保存菜单
     */
    @SecurityChecker("user:menuInfo:edit")
    @RequestMapping("/edit")
    @ResponseBody
    @OperLog(functionName = "authority.page.update", menuName = "authority.menu.menuInfo")
    public ApiBaseResponse<Boolean> editSave(MenuInfo menuInfo) {
    	try {
            menuInfo.setCreateBy(SSOClientUtils.getInstance().findCurrentUser().getUserName());
            if (StringUtils.isBlank(menuInfo.getParentId())) {
                menuInfo.setParentId(MENU_ROOT_ID);
            }
            if (StringUtils.isBlank(menuInfo.getUrl())) {
                menuInfo.setUrl("#");
            }
            menuService.saveMenuInfo(menuInfo);
            return new ApiBaseResponse<Boolean>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, 
                    Constants.API_RESPONSE_SUCCESS_MESSAGE, true);
        } catch (Exception e) {
            logger.error("insert menu info error, cause ", e);
            return new ApiBaseResponse<Boolean>(RetStatusEnum.FAIL,Constants.API_RESPONSE_FAIL_CODE, 
                    Constants.API_RESPONSE_FAIL_MESSAGE, false);
        }
    }
}
